package controllers

import (
	"net/http"
	"encoding/json"
	"git.oschina.net/YPTArch/auth/sys/logs"
	"git.oschina.net/YPTArch/auth/models"
	"git.oschina.net/YPTArch/auth/sys/config"
)


//用户登出
func Logout(w http.ResponseWriter, r *http.Request)   {
	logs.Logger.Debug("success in logout")

	var result models.Result

	var token string
	urlToken, err := getRawQueryToken(r.URL.RawQuery)
	if err != nil {
		result = models.Result{Code:models.Unauthorized, Msg:err.Error(), Data:""}
	}

	//url取到就不从header里取了
	if urlToken != "" {
		token = urlToken
	}else {
		headerToken, err := getHeaderToken(r)
		if err != nil {
			result = models.Result{Code:models.Unauthorized, Msg:err.Error(), Data:""}
		}

		if headerToken == "" {
			result = models.Result{Code:models.Unauthorized, Msg:"没有获取到token信息", Data:""}
		}else {
			token = headerToken
		}
	}


	reply, err := logoutHandler(token)
	if err != nil {
		result = models.Result{Code: models.Unauthorized, Msg: "登出处理失败！", Data: ""}
	} else {
		result = models.Result{Code: models.Ok, Msg: "登出成功！", Data: reply}
	}

	re, err := json.Marshal(result)
	if err != nil {
		logs.Logger.Error(err.Error())
		w.Write([]byte(models.ServerErr))
	}

	w.Write(re)
}

//redis删除用户
func logoutHandler(token string) (reply int, err error) {
	reply, err = models.Remove(USER+token)
	if err != nil {
		return
	}
	err = models.Delay(token, config.Conf.Expiration)
	return
}